package com.ppc.utils;

import com.ppc.properties.MinIoProperties;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidBucketNameException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.ServerException;
import io.minio.errors.XmlParserException;
import io.minio.messages.Bucket;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


/**
 * 连接minio的工具类
 *
 * @author 云诺
 * @ClassName: MinioUtils
 * @Description: (minio工具类)
 * @date 2021/1/4 18:07
 */

@Slf4j
@Component
public class MinIoUtil {

  @Autowired
  public MinIoProperties minIoProperties;

  private MinioClient minioClient;

  /**
   * 初始化
   *
   * @description
   */
  @PostConstruct
  public void init() {
    try {
      minioClient = new MinioClient(minIoProperties.getEndpoint(), minIoProperties.getAccessKey(),
          minIoProperties.getSecretKey());
      createBucket(minIoProperties.getBucketName());
    } catch (Exception e) {
      e.printStackTrace();
      log.error("初始化minio配置异常: 【{}】", e.fillInStackTrace());
    }
  }

  /**
   * 产生上传文件的动态文件名
   *
   * @param originalFilename
   * @return {@link String }
   * @description
   */
  public String updateFileName(String originalFilename) {
    UUID uuid = UUID.randomUUID();
    int lastIndexOf = originalFilename.lastIndexOf(".");
    String extension = originalFilename.substring(lastIndexOf + 1);
    String objectName =
        originalFilename.substring(0, lastIndexOf) + "&" + uuid.toString().replace("-", "") + "."
            + extension;
    return objectName;
  }

  /**
   * 获取文件链接
   *
   * @param objectName
   * @return {@link String }
   * @description
   */
  public String getFileUrl(String objectName) {
    return getFileUrl(minIoProperties.getBucketName(), objectName);
  }

  /**
   * @param bucketName : 桶名
   * @return boolean
   * @description
   */
  @SneakyThrows(Exception.class)
  public boolean bucketExists(String bucketName) {
    return minioClient.bucketExists(bucketName);
  }

  /**
   * @param bucketName : 桶名
   * @description
   */
  @SneakyThrows(Exception.class)
  public void createBucket(String bucketName) {
    boolean isExist = minioClient.bucketExists(bucketName);
    if (!isExist) {
      minioClient.makeBucket(bucketName);
    }
  }

  /**
   * @return {@link List }<{@link Bucket }>
   * @description
   */
  @SneakyThrows(Exception.class)
  public List<Bucket> getAllBuckets() {
    return minioClient.listBuckets();
  }

  /**
   * @param bucketName : 桶名
   * @param fileName   :   文件名
   * @param filePath   :   文件路径
   * @description
   */
  @SneakyThrows(Exception.class)
  public void upload(String bucketName, String fileName, String filePath) {
    minioClient.putObject(bucketName, fileName, filePath, null);
  }

  /**
   * @param bucketName : 桶名
   * @param fileName   :   文件名
   * @param stream     :     文件流
   * @return {@link String }
   * @description
   */
  @SneakyThrows(Exception.class)
  public String upload(String bucketName, String fileName, InputStream stream) {
    minioClient.putObject(bucketName, fileName, stream,
        new PutObjectOptions(stream.available(), -1));
    return getFileUrl(bucketName, fileName);
  }

  /**
   * @param file : 文件
   * @return {@link String }
   * @description
   */
  @SneakyThrows(Exception.class)
  public String upload(MultipartFile file) {
    String bucketName = minIoProperties.getBucketName();
    final InputStream is = file.getInputStream();
    final String fileName = file.getOriginalFilename();
    minioClient.putObject(bucketName, fileName, is, new PutObjectOptions(is.available(), -1));
    is.close();
    return getFileUrl(bucketName, fileName);
  }

  /**
   * @param fileName : 重命名的文件
   * @param file     :     文件
   * @return {@link String }
   * @description
   */

  public String upload(String fileName, MultipartFile file)
      throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
    String bucketName = minIoProperties.getBucketName();
    final InputStream is = file.getInputStream();
    minioClient.putObject(bucketName, fileName, is, new PutObjectOptions(is.available(), -1));
    is.close();
    return getFileUrl(bucketName, fileName);
  }

  /**
   * @param bucketName : 桶名
   * @param fileName   :   文件名
   * @description
   */
  @SneakyThrows(Exception.class)
  public void deleteFile(String bucketName, String fileName) {
    minioClient.removeObject(bucketName, fileName);
  }

  /**
   * @param bucketName : 桶名
   * @param fileName   :   文件名
   * @param response   :
   * @description
   */
  @SneakyThrows(Exception.class)
  public void download(String bucketName, String fileName, HttpServletResponse response) {
    // 获取对象的元数据
    final ObjectStat stat = minioClient.statObject(bucketName, fileName);
    response.setContentType(stat.contentType());
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition",
        "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    InputStream is = minioClient.getObject(bucketName, fileName);
    IOUtils.copy(is, response.getOutputStream());
    is.close();
  }

  /**
   * @param bucketName : 桶名
   * @param fileName   :   文件名
   * @return {@link String }
   * @description
   */
  @SneakyThrows(Exception.class)
  public String getFileUrl(String bucketName, String fileName) {
    return minioClient.presignedGetObject(bucketName, fileName);
  }

}
